const KEYS = ['hisHotels']

const getDefaultState = () => {
  const result = {}
  result.hisHotels = uni.getStorageSync('hisHotels') || []
  return result
}

const state = getDefaultState()

const mutations = {
  SET_ITEM: (state, info) => {
    if (info) {
      let origin = info.origin
      let hotel = info.hotel
      let hotel_key = origin + "_hotel"
      state[hotel_key] = hotel
      uni.setStorageSync(hotel_key, hotel)
      
      let hisHotels = state.hisHotels || []
      let exist = false
      for(let i = 0; i < hisHotels.length; i ++) {
        if (hotel.value == hisHotels[i].value) {
          exist = true
          break
        }
      }
      if (!exist) {
        hisHotels.push(hotel)
      }
      
      state['hisHotels'] = hisHotels
      uni.setStorageSync("hisHotels", hisHotels)
    } else {
      state['hisHotels'] = []
      uni.setStorageSync("hisHotels", [])
    }
  }
}

const actions = {
  add({ state, commit }, item) {
    if (item) {
      commit('SET_ITEM', item);
    }
    return new Promise(resolve => {
      resolve(item)
    })
  },
  get({ state }) {
    return new Promise(resolve => {
      resolve(state.hisHotels)
    })
  },
  clear({ state, commit }) {
    commit('SET_ITEM', '');
    return Promise.resolve()
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
